package com.ruoyi.web.controller.shop.goods;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.resp.ReplaceDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/9/2
 **/

@Api("代购菜单")
@RestController
@RequestMapping("/shop/replace")
public class ReplaceController extends BaseController {
    @Resource
    private ReplaceService replaceService;

    @Resource
    private RestaurantStoreResourceService restaurantStoreResourceService;

    @Resource
    private ApproveService approveService;

    @Resource
    private RestaurantOrderService restaurantOrderService;

    @Resource
    private RestaurantOrderDetailService restaurantOrderDetailService;

    @Log(title = "代购菜单导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Replace replace)
    {
        List<Replace> list = replaceService.selectList(replace);
        List<ReplaceDTO> replaceDTOS = fillToDTO(list);
        ExcelUtil<ReplaceDTO> util = new ExcelUtil<ReplaceDTO>(ReplaceDTO.class);
        util.exportExcel(response, replaceDTOS, "代购菜单");
    }

    @ApiOperation("分页获取代购菜单")
    @Log(title = "查询人员管理", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(Replace replace)
    {
        startPage();
        List<Replace> list = replaceService.selectList(replace);
        return getDataTable(fillToDTO(list));
    }

    @ApiOperation("获取代购菜单")
    @Log(title = "查询人员管理All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(Replace replace)
    {
        List<Replace> list = replaceService.selectList(replace);
        List<ReplaceDTO> replaceDTOS = fillToDTO(list).stream()
//                .filter(r -> "启用".equals(r.getStatus()))
//                .filter(r -> "通过".equals(r.getApproveStatus()))
                .collect(Collectors.toList());
        //app用来判断是否显示图片
        for (ReplaceDTO replaceDTO : replaceDTOS) {
            replaceDTO.setIsYn("2");
        }
        if (!"h5".equals(replace.getAppSource())) {
            return getDataTable(replaceDTOS);
        }
        List<RestaurantOrder> orders = restaurantOrderService.getNormalOrderList(RestaurantOrder.builder().type("代购订单").status("购物车").customerId(SecurityUtils.getUserId()).build());
        if (CollectionUtils.isEmpty(orders)) {
            return getDataTable(replaceDTOS);
        }
        RestaurantOrder cart = orders.get(0);
        List<RestaurantOrderDetail> orderDetails = restaurantOrderDetailService.getNormalOrderDetailList(RestaurantOrderDetail.builder().orderId(cart.getId()).build());
        if (CollectionUtils.isEmpty(orderDetails)) {
            return getDataTable(replaceDTOS);
        }
        Map<Long, ReplaceDTO> replaceDTOMap = replaceDTOS.stream().collect(Collectors.toMap(ReplaceDTO::getId, r -> r));
        for (RestaurantOrderDetail detail : orderDetails) {
            if (detail.getReplaceId() == null) {
                continue;
            }
            ReplaceDTO replaceDTO = replaceDTOMap.get(detail.getReplaceId());
            if (replaceDTO == null) {
                continue;
            }
            replaceDTO.setCount(detail.getCount() == null ? 0 : detail.getCount());
        }
        return getDataTable(replaceDTOS);
    }
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(replaceService.selectById(id));
    }

    @Log(title = "新增菜单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@Validated @RequestBody Replace replace)
    {

        String area = SecurityUtils.getUserLocation();
        if (StringUtils.isBlank(area) || area.equals("全部")) {
            throw new BaseException("园区为全部的用户无法下单");
        }

        replace.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = replaceService.create(replace);
        if (!result) {
            return error();
        }
//        ApproveMission approveMission = new ApproveMission();
//        approveMission.setApplicant(SecurityUtils.getUserId());
//        approveMission.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
//        approveMission.setStatus("审批中");
//        approveMission.setActivityType("代购菜单审批");
//        approveMission.setActivityId(replace.getId());
//        approveMission.setName("代购菜单审批");
//        approveService.createApproveMission(approveMission);
        return success();
    }

    @Log(title = "修改菜单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Replace replace) {
        replace.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = replaceService.update(replace);
        if (!result) {
            return error();
        }
//        ApproveMission approveMission = approveService.getApproveMissionByActivityd(replace.getId(), "代购菜单审批");
//        if (approveMission == null) {
//            ApproveMission approveMissionCreateDO = new ApproveMission();
//            approveMissionCreateDO.setApplicant(SecurityUtils.getUserId());
//            approveMissionCreateDO.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
//            approveMissionCreateDO.setStatus("审批中");
//            approveMissionCreateDO.setActivityType("代购菜单审批");
//            approveMissionCreateDO.setActivityId(replace.getId());
//            approveMissionCreateDO.setName("代购菜单审批");
//            approveService.createApproveMission(approveMissionCreateDO);
//        } else {
//            if ("通过".equals(approveMission.getStatus()) ||
//                    "拒绝".equals(approveMission.getStatus())) {
//                ApproveMission approveMissionCreateDO = new ApproveMission();
//                approveMissionCreateDO.setApplicant(SecurityUtils.getUserId());
//                approveMissionCreateDO.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
//                approveMissionCreateDO.setStatus("审批中");
//                approveMissionCreateDO.setActivityType("代购菜单审批");
//                approveMissionCreateDO.setActivityId(replace.getId());
//                approveMissionCreateDO.setName("代购菜单审批");
//                approveService.createApproveMission(approveMissionCreateDO);
//            }
//        }
        return success();
    }

    @Log(title = "删除人员管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(replaceService.deleteById(id));
    }

    private List<ReplaceDTO> fillToDTO(List<Replace> replaces) {
        if (CollectionUtils.isEmpty(replaces)) {
            return Collections.emptyList();
        }
        List<Long> resourceIds = replaces.stream().filter(Objects::nonNull).map(Replace::getResourceId).collect(Collectors.toList());
        List<RestaurantStoreResource> restaurantStoreResources = restaurantStoreResourceService.selectRestaurantStoreResourceByIds(resourceIds);
        Map<Long, RestaurantStoreResource> resourceMap;
        if (!CollectionUtils.isEmpty(restaurantStoreResources)) {
            resourceMap = restaurantStoreResources.stream().collect(Collectors.toMap(RestaurantStoreResource::getId, r -> r));
        } else {
            resourceMap = new HashMap<>();
        }
        List<ReplaceDTO> replaceDTOS = replaces.stream().filter(Objects::nonNull).map(r -> {
            ReplaceDTO replaceDTO = new ReplaceDTO();
            replaceDTO.setId(r.getId());
            replaceDTO.setResourceId(r.getResourceId());
            replaceDTO.setResourceName(Optional.ofNullable(resourceMap.get(r.getResourceId())).map(RestaurantStoreResource::getName).orElse(null));
            replaceDTO.setName(Optional.ofNullable(resourceMap.get(r.getResourceId())).map(RestaurantStoreResource::getName).orElse(null));
            replaceDTO.setImage(Optional.ofNullable(resourceMap.get(r.getResourceId())).map(RestaurantStoreResource::getImageUrl).orElse(null));
            replaceDTO.setType(r.getType());
            replaceDTO.setPrice(r.getPrice());
            replaceDTO.setUnit(r.getUnit());
            replaceDTO.setStatus(r.getStatus());
            replaceDTO.setCreateBy(r.getCreateBy());
            replaceDTO.setCreateTime(r.getCreateTime());
            replaceDTO.setUpdateBy(r.getUpdateBy());
            replaceDTO.setUpdateTime(r.getUpdateTime());
            replaceDTO.setRemark(Optional.ofNullable(resourceMap.get(r.getResourceId())).map(RestaurantStoreResource::getRemark).orElse(null));
//            ApproveMission approveMission = approveService.getApproveMissionByActivityd(r.getId(), "代购菜单审批");
//            if (approveMission == null) {
//                replaceDTO.setApproveStatus("未提交审批");
//            } else {
//                replaceDTO.setApproveStatus(approveMission.getStatus());
//                replaceDTO.setApproveMissionId(approveMission.getId());
//            }
            return replaceDTO;
        }).collect(Collectors.toList());
        PageInfo<Replace> oldPage = new PageInfo<>(replaces);
        Page<ReplaceDTO> newPage = new Page<>();
        newPage.addAll(replaceDTOS);
        newPage.setTotal(oldPage.getTotal());
        return newPage;
    }
}
